package com.study.chapter05.operator.sink;

import com.study.entity.Event;
import com.study.chapter05.source.ClickSource;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;

/**
 * @Description:
 * @Author: LiuQun
 * @Date: 2022/7/30 16:58
 */
public class Sink2RedisTest {
    public static void main(String[] args) throws Exception {
        //环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<Event> stream = env.addSource(new ClickSource());

        //1.创建一个到redis连接的配置
        FlinkJedisPoolConfig redisConfig = new FlinkJedisPoolConfig
                .Builder()
                .setHost("192.168.30.236")
                .setPort(6379)
                .setPassword("123456")
                .build();

        //将数据保存到redis
        stream.addSink(new RedisSink<>(redisConfig,new MyRedisMapper()));

        env.execute();
    }

    public static class MyRedisMapper implements RedisMapper<Event>{

        @Override
        public RedisCommandDescription getCommandDescription() {
            //redis命令的描述，将数据保存在key为clicks的hash表中
            return new RedisCommandDescription(RedisCommand.HSET,"clicks");
        }

        @Override
        public String getKeyFromData(Event event) {
            return event.getUser();
        }

        @Override
        public String getValueFromData(Event event) {
            return event.getUrl();
        }
    }
}
